const app = getApp();
class wxRequest {
  //不需要获取tonken
  wxAjax(params, callBack) {
    if (params.loading != false) {
      wx.showLoading({
        title: '数据加载中',
      })
    }

    var that = this;
    if (!params.method) {
      params.method = 'get'
    }
    var token = "";
    if (params.token) {
      token = wx.getStorageSync("Authorization") || ""
    }

    // content-type类型默认json格式
    if (!params.contentType) {
      params.contentType = 'application/json'
    }

    let header = {
      'content-type': params.contentType,
    }
    if (token) {
      header.Authorization = token
    }

    wx.request({
      url: params.url,
      data: params.data,
      method: params.method,
      header,
      success: function(res) {
        wx.hideLoading()
        var resdata = res.data
        if (resdata.success) {
          callBack && callBack(resdata.datas);
        } else {
          wx.hideLoading()
          if (resdata.errCode == "AUTH1002" || resdata.errCode == "AUTH1001" || resdata.errCode == "AUTH1003") {
            wx.redirectTo({
              url: '/pages/login/login',
            })
            return //防止多次请求 
          } else {
            wx.showToast({
              title: resdata.errMsg || '请求失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      },
      fail: function(err) {
        wx.hideLoading()
      }
    });
  }

  //需要获取tonken
  wxTonkenAjax(params, callBack) {
    var token = wx.getStorageSync('Authorization');

    // 获取当前页面的路由
    // let pages = getCurrentPages();
    // let currPage = null; 
    // if (pages.length) { 
    //   currPage = pages[pages.length - 1];
    // } 
    // let route = currPage.route
    // let options = this.qsurl(currPage.options)
    // console.log(route, options,'route')
    let route = this.getCurrentPageUrlWithArgs()
    wx.setStorageSync('prePage', route)


    if (!token) {
      //没token值直接跳转到登陆
      wx.redirectTo({
        url: '/pages/login/login',
      })
      return //防止多次请求

    } else {
      if (params.loading != false) {
        wx.showLoading({
          title: '数据加载中',
        })
      }
      this.request(params, callBack);
    }
  }

  //请求接口
  request(params, callBack) {
    var that = this;
    // 默认get
    if (!params.method) {
      params.method = 'get'
    }
    // content-type类型默认json格式
    if (!params.contentType) {
      params.contentType = 'application/json'
    }
    wx.request({
      url: params.url,
      data: params.data,
      method: params.method,
      header: {
        'content-type': params.contentType,
        'Authorization': wx.getStorageSync('Authorization')
      },
      success: function(res) {
        wx.hideLoading()
        var resdata = res.data
        if (resdata.success) {
          callBack && callBack(resdata.datas);
        } else {
          if (resdata.errCode == "AUTH1002" || resdata.errCode == "AUTH1001" || resdata.errCode == "AUTH1003") {
            wx.redirectTo({
              url: '/pages/login/login',
            })
            return
          } else {
            wx.showToast({
              title: resdata.errMsg || '请求失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      },
      fail: function(err) {
        wx.hideLoading()
        console.log('fail')
      }
    });
  }

  //重新回调
  refetch(params, callBack) {
    var that = this
    that.wxlogin((Authorization) => {
      that.request(params, callBack);
    });
  }

  // 登录处理
  wxlogin(callBack) {
    var that = this;
    wx.login({
      success: function(res) {
        wx.request({
          url: app.globalData.apiUrl + '/user/weixinLogin2',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded',
          },
          data: {
            code: res.code,
          },
          success: function(result) {
            //"4900", "TOKEN(登录)过期"，//"4901", "TOKEN无效"，//"4010", "未认证"
            var resdata = res.data
            if (resdata.success) {
              wx.setStorageSync('userInfo', '')
              wx.setStorageSync('Authorization', resdata.datas.Authorization);
              callBack && callBack(resdata.datas);
            } else {
              wx.showToast({
                title: resdata.errMsg,
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      }
    })
  }

  //判断是否授权
  authorizeLogin() {
    if (!wx.getStorageSync('userInfo') || !wx.getStorageSync('binded')) {
      wx.removeStorageSync('userInfo')
      wx.removeStorageSync('permissions')
      wx.navigateTo({
        url: '/pages/login/login',
      })
      return false;
    } else {
      return true;
    }
  }

  urlScene(scene) {
    var params = new Object,
      aParams = scene.split("&");
    for (var i = 0; i < aParams.length; i++) {
      var aParam = aParams[i].split("=");
      params[aParam[0]] = aParam[1]
    }
    return params
  }

  //获取小程序当前页面完整路径
  getCurrentPageUrlWithArgs() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    const url = currentPage.route
    const options = currentPage.options
    let urlWithArgs = `/${url}?`
    for (let key in options) {
      const value = options[key]
      urlWithArgs += `${key}=${value}&`
    }
    urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
    return urlWithArgs 
  }


}

module.exports = {
  wxRequest
};